﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using mediaPrime.Controls.FluidKit.Controls;
using mediaPrime.Core.UserControls;
using mediaPrime.Sdk;

namespace mediaPrime.Core
{
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private HomeUserControl homeUserControl;
        private ContentPresenter currentContentPresenter;
        private FlipTransition flipTransitionLeft;
        private FlipTransition flipTransitionRight;
        private FadeTransition fadeTransition;

        private Plugin currentPlugin;

        private WindowContent currentWindowContent;
        internal ExtensionManager PluginManager { get; set; }
        public MessageHandler MessageHandler { get; set; }

        public MainWindow()
        {
            InitializeComponent();

#if DEBUG
            Topmost = false;
#endif

            // Initialize MessageHandler to handle all messages
            MessageHandler = new MessageHandler(this);

            // Initialize PluginManager to handle Plugins
            PluginManager = new ExtensionManager(Pathes.ExtensionsDir, App.Version);
            PluginManager.MessageSent += pluginManager_MessageSent;
            PluginManager.MessageWithResultSent += pluginManager_MessageWithResultSent;

            // TODO: Only load Plugins which are enabled by the user

            // Initialize TransitionPresenter     
            currentContentPresenter = contentPresenter1;
            flipTransitionRight = new FlipTransition() { Rotation = Direction.RightToLeft };
            flipTransitionLeft = new FlipTransition() { Rotation = Direction.LeftToRight };
            fadeTransition = new FadeTransition() { Duration = new Duration(TimeSpan.FromMilliseconds(500)) };

            this.Loaded += MainWindow_Loaded;
        }

        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            ShowHome(true);
        }

        /// <summary>
        /// A Plugin has sent a message
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">Message</param>
        private void pluginManager_MessageSent(object sender, MessageEventArgs e)
        {
            MessageHandler.HandleMessage(e.Message);
        }

        private object pluginManager_MessageWithResultSent(object sender, MessageEventArgs e)
        {
            return MessageHandler.HandleMessageWithResult(e.Message);
        }


        public void ShowHome(bool firstTime = false)
        {
            if (homeUserControl == null)
                homeUserControl = new HomeUserControl(this);

            if (currentPlugin != null && currentWindowContent == WindowContent.Plugin)
            {
                currentPlugin.OnHide();
                currentPlugin = null;
            }

            currentWindowContent = WindowContent.Home;

            if (firstTime)
                ApplyTransition(homeUserControl, fadeTransition);
            else
                ApplyTransition(homeUserControl, flipTransitionLeft);
        }

        public void ShowPlugin(string pluginId)
        {
            var plugin = PluginManager.LoadPluginById(pluginId);
            if (plugin != null)
            {
                var userInterface = plugin.GetUserInterface();

                currentPlugin = plugin;
                currentPlugin.OnShow();

                currentWindowContent = WindowContent.Plugin;

                ApplyTransition(userInterface as FrameworkElement, flipTransitionRight);
            }
        }

        public void ApplyTransition(FrameworkElement content, Transition transition)
        {
            transitionPresenter.Transition = transition;

            if (currentContentPresenter == contentPresenter1)
            {
                contentPresenter2.Content = content;
                transitionPresenter.ApplyTransition(contentPresenter1, contentPresenter2);
                currentContentPresenter = contentPresenter2;
            }
            else
            {
                contentPresenter1.Content = content;
                transitionPresenter.ApplyTransition(contentPresenter2, contentPresenter1);
                currentContentPresenter = contentPresenter1;
            }
        }

        private void transitionPresenter_TransitionCompleted(object sender, EventArgs e)
        {
            // Set focus to Plugin / UserControl
            var traversalRequest = new TraversalRequest(FocusNavigationDirection.Next);
            MoveFocus(traversalRequest);
        }

        private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                e.Handled = true;

                if (currentWindowContent == WindowContent.Plugin)
                    ShowHome();
                else
                    ShowExitDialog();
            }
        }

        public void ShowExitDialog()
        {
            var dlg = new Dialogs.ExitDialog();
            dlg.ShowDialog();
        }
    }

    public enum WindowContent
    {
        Home, Plugin
    }
}
